package com.ruoyi.common.core.utils.bean;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.*;

/**
 * @Description :
 * @Author: xuxiaojun
 * @Date: Created in 2020/5/26 16:37
 */
public class ConvertUtils {
    /**
     * Bean 转成 Bean ， 属性不必对应
     * @param srcObj
     * @param destObj
     */
    public static  void  copyBeanToBean(Object srcObj,Object destObj){
        Map<String, Object> srcMap = new HashMap<String, Object>();
        Field[] srcFields2 = srcObj.getClass().getDeclaredFields();
        Field[] srcFields1 = srcObj.getClass().getFields();
        Field[] srcFields = getAllFields(srcObj.getClass());
        for (Field srcField : srcFields) {
            try {

                // 去除 static final 属性（ serialVersionUID ）
                if (Modifier.isFinal(srcField.getModifiers())){
                    continue;
                }
                srcField.setAccessible(true);
                srcMap.put(srcField.getName(), srcField.get(srcObj)); // 获取属性值
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        Field[] destFields = getAllFields(destObj.getClass());

        for (Field destField : destFields) {
            destField.setAccessible(true);
            if (srcMap.get(destField.getName()) == null) {
                continue;
            }
            try {
                destField.set( destObj, srcMap.get( destField.getName() ) ); // 给属性赋值
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * Map 转成 Bean ， 属性不必对应
     * @param srcMap
     * @param destObj
     */
    public static void copyMapToBean(Map<String,Object> srcMap,Object destObj){

        Field[] destFields = getAllFields(destObj.getClass());

        for ( Field destField : destFields ) {
            destField.setAccessible(true);
            if (srcMap.get(destField.getName()) == null) {
                continue;
            }
            try {
                destField.set(destObj, srcMap.get(destField.getName())); //给属性赋值
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取该类的属性及父类属性
     * @param clazz
     * @return
     */
    private static Field[] getAllFields(Class<?> clazz) {
        List<Field> fieldList = new ArrayList<>();
        while (clazz != null){
            fieldList.addAll(new ArrayList<>(Arrays.asList(clazz.getDeclaredFields())));
            clazz = clazz.getSuperclass();
        }
        Field[] fields = new Field[fieldList.size()];
        return fieldList.toArray(fields);
    }
}